<script setup lang="ts">
import { useLoginStore } from '@/stores'
import { ElMessage, type FormInstance } from 'element-plus'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { loginFormRules } from '@/utils/rules'

const store = useLoginStore()
const route = useRoute()
const router = useRouter()

const loading = ref(false)
const loginFormRef = ref<FormInstance>()
const onLogin = async () => {
  await loginFormRef.value?.validate()
  try {
    loading.value = true
    await store.loginByPasswordAction()
    ElMessage({ type: 'success', message: '登陆成功' })
    await router.replace((route.query.returnUrl as string) || '/')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login-panel-page" @keydown.enter="onLogin">
    <div class="content">
      <h1 class="title">登录</h1>
      <el-form class="login-form" :model="store.account" :rules="loginFormRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input prefix-icon="User" v-model="store.account.username" placeholder="账号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="Lock" clearable show-password v-model="store.account.password" placeholder="密码" type="password" />
        </el-form-item>
        <div class="btn-group">
          <el-checkbox v-model="store.isRemPwd" label="记住密码" class="rempwd-checkbox" />
          <el-button type="primary" style="margin: 0" link>忘记密码</el-button>
        </div>
        <el-button class="login-btn" type="primary" @click="onLogin" :loading="loading">登录</el-button>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-panel-page {
  /* login-card */
  width: 400px;
  height: 375px;
  border-radius: 4px;
  opacity: 1;

  /* 自动布局 */
  display: flex;
  flex-direction: column;
  padding: 40px 50px;

  box-sizing: border-box;
  /* 边框/一般 */
  border: 1px solid #e5e6eb;

  /* 外阴影/普通 */
  box-shadow: var(--bc-box-shadow-light);

  .content {
    /* 自动布局子元素 */
    width: 300px;
    height: 295px;
    opacity: 1;

    /* 自动布局 */
    display: flex;
    gap: 30px;
    flex-direction: column;

    .login-form {
      /* login-form */
      width: 100%;
      height: 224px;
      opacity: 1;

      /* 自动布局 */
      display: flex;
      flex-direction: column;
      gap: 16px;
      align-self: stretch;

      z-index: 1;

      .btn-group {
        width: 100%;
        height: 32px;
        opacity: 1;

        /* 自动布局 */
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 0px;
        gap: 13px;
        align-self: stretch;

        z-index: 2;

        .rempwd-checkbox {
          flex: 1;
        }
      }
      .login-btn {
        margin: 0;
      }
    }
  }
}

.title {
  margin-bottom: 20px;
  font-weight: normal;
  font-size: var(--bc-text-size6);
}

.el-form-item {
  margin-bottom: 0;
}
</style>
